package com.finance.console.storage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    // 数据库连接参数（修正主机名空格问题，使用localhost）
    private static final String URL = "jdbc:mysql://localhost:3306/finance_db?useSSL=false&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PWD = "123456Ljx";

    // 获取数据库连接
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USER, PWD);
        } catch (SQLException e) {
            // 更详细的错误信息，便于排查（如主机不可达、密码错误等）
            throw new RuntimeException("数据库连接失败：URL=" + URL + ", USER=" + USER, e);
        }
    }

    // 关闭数据库连接
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                if (!conn.isClosed()) { // 检查连接是否已关闭
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException("关闭数据库连接失败", e);
            }
        }
    }
}